package com.lottery.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.entity.LotteryRecord;
import com.lottery.entity.Prize;
import com.lottery.entity.User;
import com.lottery.repository.LotteryRecordRepository;
import com.lottery.repository.PrizeRepository;
import com.lottery.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AdminService {

    @Autowired
    private PrizeRepository prizeRepository;

    @Autowired
    private LotteryRecordRepository lotteryRecordRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LotteryService lotteryService;

    /**
     * 创建奖品
     */
    public Prize createPrize(Prize prize) {
        // 如果没有设置剩余数量，则默认等于总数量
        if (prize.getRemaining() == null) {
            prize.setRemaining(prize.getQuantity());
        }
        prizeRepository.insert(prize);
        return prize;
    }

    /**
     * 更新奖品
     */
    public Prize updatePrize(Long id, Prize prizeDetails) {
        Prize prize = prizeRepository.selectById(id);
        if (prize == null) {
            throw new RuntimeException("奖品不存在");
        }

        prize.setName(prizeDetails.getName());
        prize.setProbability(prizeDetails.getProbability());
        prize.setQuantity(prizeDetails.getQuantity());
        prize.setRemaining(prizeDetails.getRemaining());
        prize.setImageUrl(prizeDetails.getImageUrl());
        prize.setDescription(prizeDetails.getDescription());

        prizeRepository.updateById(prize);
        return prize;
    }

    /**
     * 删除奖品
     */
    public void deletePrize(Long id) {
        Prize prize = prizeRepository.selectById(id);
        if (prize == null) {
            throw new RuntimeException("奖品不存在");
        }
        prizeRepository.deleteById(id);
    }

    /**
     * 获取所有奖品
     */
    public List<Prize> getAllPrizes() {
        return prizeRepository.selectList(null);
    }

    /**
     * 获取奖品详情
     */
    public Prize getPrizeById(Long id) {
        Prize prize = prizeRepository.selectById(id);
        if (prize == null) {
            throw new RuntimeException("奖品不存在");
        }
        return prize;
    }

    /**
     * 获取所有抽奖记录（分页）
     */
    public Page<LotteryRecord> getAllLotteryRecords(Page<LotteryRecord> page) {
        return lotteryRecordRepository.selectPage(page, null);
    }

    /**
     * 获取中奖记录
     */
    public List<LotteryRecord> getWinningRecords(Long userId) {
        return lotteryRecordRepository.findByUserIdAndIsWinnerTrueOrderByCreatedAtDesc(userId);
    }

    /**
     * 获取统计数据
     */
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        long totalUsers = userRepository.selectCount(null);
        stats.put("totalUsers", totalUsers);
        
        // 总抽奖次数
        long totalLotteries = lotteryRecordRepository.selectCount(null);
        stats.put("totalLotteries", totalLotteries);
        
        // 总中奖次数
        long totalWinnings = lotteryRecordRepository.countWinningRecords();
        stats.put("totalWinnings", totalWinnings);
        
        // 中奖率
        double winRate = totalLotteries > 0 ? (double) totalWinnings / totalLotteries * 100 : 0;
        stats.put("winRate", Math.round(winRate * 100.0) / 100.0);
        
        // 总奖品数
        long totalPrizes = prizeRepository.selectCount(null);
        stats.put("totalPrizes", totalPrizes);
        
        // 剩余奖品数
        long remainingPrizes = prizeRepository.findAvailablePrizes().stream()
                .mapToLong(Prize::getRemaining)
                .sum();
        stats.put("remainingPrizes", remainingPrizes);
        
        return stats;
    }

    /**
     * 为用户增加抽奖次数
     */
    public void addUserChances(Long userId, int chances) {
        lotteryService.addUserChances(userId, chances);
    }

    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return userRepository.selectList(null);
    }

    /**
     * 获取用户详情
     */
    public User getUserById(Long id) {
        User user = userRepository.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    /**
     * 获取指定时间范围内的抽奖记录
     */
    public List<LotteryRecord> getLotteryRecordsByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return lotteryRecordRepository.findByCreatedAtBetween(startDate, endDate);
    }
}